# -*- coding: utf-8 -*-
# בש״ד
#
# Miraflores Blog for Django - Part of the Cuba Libre Project
# Copyright (C) 2009, Joshua "jag" Ginsberg <jag@flowtheory.net>
# 
# Por mi amor, que inspira a mi cada respiración y que echa de Cuba
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import urlparse
from django.core.urlresolvers import reverse
from django.core.mail import mail_admins
from django.contrib.comments.moderation import CommentModerator
from django.contrib.comments.models import CommentFlag
from django.contrib.sites.models import Site
from django.conf import settings as site_settings
from miraflores import settings

class AkismetModerator(CommentModerator):
    
    def _akismet(self, comment, content_obj, request):
        # returns True if the comment is okay, False if the comment is not
        # this is the opposite of what the akismet API does
        try:
            from akismet import Akismet
        except ImportError:
            return True
        if not settings.AKISMET_API_KEY:
            return True
        print 'Akismet enabled'
        base_url = urlparse.urlunsplit((
            (request.is_secure() and 'https') or 'http', 
            Site.objects.get_current().domain, 
            reverse('miraflores_blog_entry_list'), '', ''))
        kizzer = Akismet(
            key=settings.AKISMET_API_KEY,
            blog_url=base_url
        )
        if kizzer.verify_key():
            print 'Key verified'
            query = {
                'user_ip': request.META.get('REMOTE_ADDR', '127.0.0.1'),
                'user_agent': request.META.get('HTTP_USER_AGENT', ''),
                'referrer': request.META.get('HTTP_REFERER', ''),
                'comment_type': 'comment',
                'comment_author': comment.user_name.encode('utf8')
            }
            return not kizzer.comment_check(comment.comment.encode('utf8'),
                                            data=query, build_data=True)
        else:
            if site_settings.DEBUG:
                raise ValueError, u'The Akismet key provided is invalid.'
            else:
                mail_admins(u'Akismet API key failed',
                            u'The Akismet API key failed verification.',
                            fail_silently=True)
                return True
    
    def allow(self, comment, content_obj, request):
        # Returns True to allow, False to discard
        super_result = super(AkismetModerator, self).allow(
            comment, content_obj, request)
        if super_result and settings.REJECT_AKISMET_FLAGGED:
            return self._akismet(comment, content_obj, request)
        else:
            return super_result
    
    def moderate(self, comment, content_obj, request):
        # Returns True to moderate, False to let slide
        super_result = super(AkismetModerator, self).moderate(
            comment, content_obj, request)
        return super_result or not self._akismet(comment, content_obj, request)
            
def _akismet_report(request, comment_obj, method):
    try:
        from akismet import Akismet
    except ImportError:
        return True
    if not settings.AKISMET_API_KEY:
        return True
    base_url = urlparse.urlunsplit((
        (request.is_secure() and 'https') or 'http', 
        Site.objects.get_current().domain, 
        reverse('miraflores_blog_entry_list'), '', ''))
    kizzer = Akismet(
        key=settings.AKISMET_API_KEY,
        blog_url=base_url
    )
    if kizzer.verify_key():
        query = {
            'user_ip': comment_obj.ip_address,
            'user_agent': '',
            'referrer': '',
            'comment_type': 'comment',
            'comment_author': comment_obj.user_name.encode('utf8')
        }
        fn = getattr(kizzer, method)
        fn(comment_obj.comment.encode('utf8'), data=query, build_data=True)

def report_comment_as_spam(request, comment_obj):
    _akismet_report(request, comment_obj, 'submit_spam')
    comment_obj.flags.create(flag=CommentFlag.MODERATOR_DELETION,
                             user=request.user)
    comment_obj.is_public = False
    comment_obj.is_removed = True
    comment_obj.save()

def report_comment_as_ham(request, comment_obj):
    _akismet_report(request, comment_obj, 'submit_ham')
    comment_obj.flags.filter(flag=CommentFlag.MODERATOR_DELETION).delete()
    comment_obj.flags.create(flag=CommentFlag.MODERATOR_APPROVAL,
                             user=request.user)
    comment_obj.is_public = True
    comment_obj.is_removed = False
    comment_obj.save()
